package com.yyfax.ph.personal.subaccount;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.view.View;
import android.widget.TextView;
import butterknife.BindView;
import com.aspsine.irecyclerview.IRecyclerView;
import com.aspsine.irecyclerview.OnLoadMoreListener;
import com.aspsine.irecyclerview.OnRefreshListener;
import com.yyfax.common.recycler.StatesAdapter;
import com.yyfax.common.recyclerview.Divider;
import com.yyfax.common.recyclerview.FooterLoadMoreView;
import com.yyfax.common.tools.DensityUtil;
import com.yyfax.common.tools.RobolectricUtils;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.ph.R;
import com.yyfax.ph.base.adapter.BaseRetryRecyclerAdapter;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.base.BaseYYFaxActivity;
import com.yyfax.ph.personal.entrydetail.EntryDetailActivity;

import java.util.List;

/**
 * 子账号管理
 * Created by zhangxian on 2017/11/3.<br>
 * Copyright 2017 www.yylending.com. All Rights Reserved.<br><br>
 */

public class SubAccountActivity extends BaseYYFaxActivity implements SubAccountPresenter.View,
		SubAccountAdapter.SubAccountDetailItemClickListener, OnRefreshListener, OnLoadMoreListener, BaseRetryRecyclerAdapter.RetryClickListener {
	private static final String TAG = SubAccountActivity.class.getSimpleName();

	private static final int LOADER_ID = 602;

	/**
	 * 公司名称
	 */
	@BindView(R.id.company_name_tv)
	TextView mCompanyNameTv;

	/**
	 * 子账户数量
	 */
	@BindView(R.id.sub_account_tv)
	TextView mSubAccountTv;

	/**
	 * 子账户进件总量
	 */
	@BindView(R.id.sub_apply_account_tv)
	TextView mSubApplyAccountTv;

	@BindView(R.id.sub_account_lv)
	IRecyclerView mSubAccountLv;

	private SubAccountAdapter mAdapter;
	private BaseRetryRecyclerAdapter mViewStateAdapter;

	private FooterLoadMoreView mLoadMoreView;

	private int mPageNum = 1;
	private int mPageSize = 20;

	private SubAccountPresenter mPresenter;

	public static void start(Activity aty) {
		Intent intent = new Intent(aty, SubAccountActivity.class);
		aty.startActivity(intent);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return new PresenterLoader<>(this, new SubAccountPresenter.Generator());
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		mPresenter = (SubAccountPresenter) data;
		mPresenter.attach(this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		getSupportLoaderManager().destroyLoader(LOADER_ID);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getSupportLoaderManager().initLoader(LOADER_ID, null, this);
	}

	@Override
	public int getContentViewRes() {
		return R.layout.sub_account_activity_layout;
	}

	@Override
	public void initContentView() {
		setTitle(R.string.sub_account_manage);
		mCompanyNameTv.setText(YJPH.getInstance().getPreferenceManager().getUserName());
		mLoadMoreView = (FooterLoadMoreView) mSubAccountLv.getLoadMoreFooterView();
		mSubAccountLv.setLayoutManager(new GridLayoutManager(this, 1));
		mSubAccountLv.addItemDecoration(new Divider(DensityUtil.dip2px(this, 0.5f), YJPH.getInstance().color(R.color.color_e6e6e6), false, 0, 0, 0, 0, 0));

		mAdapter = new SubAccountAdapter();
		mAdapter.setListener(this);
		View noNetworkLayout = getLayoutInflater().inflate(R.layout.state_view_no_network, mSubAccountLv, false);
		View emptyLayout = getLayoutInflater().inflate(R.layout.sub_account_state_view_no_data, mSubAccountLv, false);
		mViewStateAdapter = new BaseRetryRecyclerAdapter(mAdapter, null, emptyLayout, noNetworkLayout);
		mViewStateAdapter.setRetryClickListener(this);
		mSubAccountLv.setIAdapter(mViewStateAdapter);

		mSubAccountLv.setOnRefreshListener(this);
		mSubAccountLv.setOnLoadMoreListener(this);
		mSubAccountLv.post(new Runnable() {
			@Override
			public void run() {
				if (!RobolectricUtils.isARobolectricUnitTest()) {
					mSubAccountLv.setRefreshing(true);
				}
			}
		});
	}

	@Override
	public void onBackBtnPressed() {
		super.onBackBtnPressed();
		finish();
	}

	@Override
	public void onDetailItemClick(SubAccountModel.SubAccountBean bean) {
		Intent i = new Intent(this, EntryDetailActivity.class);
		i.putExtra(EntryDetailActivity.SUB_USER_ID, bean.userId);
		i.putExtra(EntryDetailActivity.NAME, bean.name);
		i.putExtra(EntryDetailActivity.BIND_DATE, bean.bindTime);
		i.putExtra(EntryDetailActivity.APPLY_COUNT, bean.applyCount);
		i.putExtra(EntryDetailActivity.LOAN_COUNT, bean.loanCount);
		EntryDetailActivity.start(this, i);
	}

	//下拉刷新
	@Override
	public void refreshSuccess(int count, int applyCount, List<SubAccountModel.SubAccountBean> list) {
		refreshFinish();
		mAdapter.removeAll();
		if (null != list && list.size() > 0) {
			mViewStateAdapter.setState(StatesAdapter.STATE_NORMAL);
			mAdapter.addData(list);
			mAdapter.notifyDataSetChanged();
		} else {
			mViewStateAdapter.setState(StatesAdapter.STATE_EMPTY);
		}
		mSubAccountLv.scrollToPosition(0);
		mSubAccountTv.setText(String.valueOf(count));
		mSubApplyAccountTv.setText(String.valueOf(applyCount));
	}

	//上拉加载
	@Override
	public void loadmoreSuccess(List<SubAccountModel.SubAccountBean> list) {
		mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
		if (null == list || list.size() == 0) {
			showToast(R.string.has_no_more);
		} else {
			mViewStateAdapter.setState(StatesAdapter.STATE_NORMAL);
			mAdapter.addData(list);
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void getSubAccountFailure(String tips) {
		mPageNum--;
		refreshFinish();
		mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
		if (mPageNum == 1) {
			changeViewState(true);
			showToast(R.string.load_failed);
		}
	}

	@Override
	public void onRefresh() {
		loadPage(true);
		mSubAccountLv.setRefreshing(true);
	}

	@Override
	public void onLoadMore() {
		if ((mAdapter.getCount() % mPageSize) == 0) {
			mLoadMoreView.setStatus(FooterLoadMoreView.Status.LOADING);
			loadPage(false);
		} else {
			mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
			showToast(R.string.has_no_more);
		}
	}

	private void loadPage(boolean isRefresh) {
		mPageNum = isRefresh ? 1 : ++mPageNum;
		mPresenter.getSubAccounts(mPageNum, mPageSize, isRefresh);
	}

	private void refreshFinish() {
		mSubAccountLv.post(new Runnable() {
			@Override
			public void run() {
				mSubAccountLv.setRefreshing(false);
			}
		});
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips) {
		super.onFunctionalError(e, autoTips);
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				changeViewState(true);
			}
		});
	}

	private void changeViewState(boolean isLoadDataError) {
		if (mPageNum == 1) {
			refreshFinish();
			if (isLoadDataError) {
				mViewStateAdapter.setState(StatesAdapter.STATE_ERROR);
			} else {
				mViewStateAdapter.setState(StatesAdapter.STATE_EMPTY);
			}
		}
	}

	@Override
	public void onRetry() {
		onRefresh();
	}
}
